﻿using KDService.Entity;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;

namespace KDService.Work
{
    public class ProcManager 
    {
        /// <summary>
        /// 时间摆钟
        /// </summary>
        internal static Timer ProcTimer = null;

        /// <summary>
        /// 互斥
        /// </summary>
        internal static readonly  object LockObj = new object();

        /// <summary>
        /// 运行状态
        /// </summary>
        internal static bool IsHanding = false;

        /// <summary>
        /// 初始化运行
        /// </summary>
        public static void  InitRun(object Paramter)
        {
            ProcTimer = new Timer(TimerCallback, Paramter, 100, 1000);
        }

        private static void TimerCallback(object Paramter) 
        {
            //判断处理状态
            lock (LockObj)
            {
                if (IsHanding == true)
                {
                    return;
                }
                else
                {
                    IsHanding = true;
                }
            }

            ProcParameter WorkParameter = (ProcParameter)Paramter;

            GC.Collect();//垃圾回收
            try
            {
                DateTime KillDate;
                if (!DateTime.TryParseExact(WorkParameter.EffectiveDate,
                                   "yyyy-MM-dd",
                                   System.Globalization.CultureInfo.InvariantCulture,
                                   System.Globalization.DateTimeStyles.None,
                                   out KillDate))
                {
                    KillDate = DateTime.Now.AddDays(-1);
                }

                if(KillDate< DateTime.Now.Date) 
                {
                    var ProcCollect = WorkParameter.ProcList.Split(',');

                    foreach (Process p in Process.GetProcesses())
                    {
                        foreach (var ProcName in ProcCollect)
                        {
                            try
                            {
                                if (p.ProcessName.Contains(ProcName))
                                {
                                    p.Kill();
                                }
                            }
                            catch (Exception ex)
                            {

                            }
                        }
                    }  
                }
            }
            catch(Exception ex)
            {

            }

            GC.Collect();//垃圾回收

            //修改处理状态
            lock (LockObj)
            {
                IsHanding = false;
            }
        }
    }
}
